package com.redisdemo.demo.util;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;


/**
 * @author tengfei
 * @version 1.0
 * @date 2018/7/13 下午4:15
 */
public class JedisUtil {

    private  static JedisPool jedisPool;
    static{
        String ip = "127.0.0.1";
        int port = 6379;
        String password = "";
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(256);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        config.setTestWhileIdle(true);
        config.setMinEvictableIdleTimeMillis(60000L);
        config.setTimeBetweenEvictionRunsMillis(3000L);
        config.setNumTestsPerEvictionRun(-1);
        if (password != null && !"".equals(password)) {
            // redis 设置了密码
            jedisPool = new JedisPool(config, ip, port, 10000, password);
        } else {
            // redis 未设置密码
            jedisPool = new JedisPool(config, ip, port, 10000);
        }
    }

    /**
     * 存储REDIS队列 顺序存储
     * @param  key reids键名
     * @param  value 键值
     */
    public static void lpush(byte[] key, byte[] value) {

        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.lpush(key, value);
        } catch (Exception e) {
            //释放redis对象
            e.printStackTrace();
        } finally {
            //返还到连接池
            if(jedis!=null){
                jedis.close();
            }
        }
    }

    /**
     * 存储REDIS队列 反向存储
     * @param  key reids键名
     * @param  value 键值
     */
    public static void rpush(byte[] key, byte[] value) {

        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.rpush(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //返还到连接池
            if(jedis!=null){
                jedis.close();
            }
        }
    }

    /**
     * 获取队列数据
     * @param  key 键名
     * @return
     */
    public static List<byte[]> brpop(byte[] key) {

        List<byte[]> bytes1=null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            bytes1=jedis.brpop(0,key);
        } catch (Exception e) {
            //释放redis对象
            jedis.close();
            e.printStackTrace();
        } finally {
            if(jedis!=null){
                jedis.close();
            }
        }
        return bytes1;
    }

    public static byte[] rpop(byte[] key) {

        byte[] bytes = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            bytes = jedis.rpop(key);
        } catch (Exception e) {
            //释放redis对象
            jedis.close();
            e.printStackTrace();
        } finally {
            if(jedis!=null){
                jedis.close();
            }
        }
        return bytes;
    }



}